package com.cx.filter;

import cn.hutool.core.util.ObjectUtil;
import com.cx.pojo.LoginUserDetails;
import com.cx.pojo.User;
import com.cx.properties.JwtProperties;
import com.cx.util.JwtUtil;
import com.cx.util.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;



@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private  RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求头的token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            /*
                没获取到token，直接放行,因为在SpringSecurityConfig中的securityFilterChain(HttpSecurity http)方法中配置了拦截，
                只有通过认证(携带token的请求)的用户才会放行
             */
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token
        Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
        Long userId = Long.valueOf(claims.get("userId").toString());

        // 用户登录
        LoginUserDetails loginUserDetails = (LoginUserDetails) redisTemplate.opsForValue().get("user:login:" + userId);
        if (Objects.isNull(loginUserDetails)) {
            throw new RuntimeException("用户未登录！");
        }



        // 将user对象存入SecurityContextHolder中
        //  获取权限信息封装到UsernamePasswordAuthenticationToken中
        // UsernamePasswordAuthenticationToken:该方法的第三个参数就是标记该用户已经认证过了
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUserDetails, null, loginUserDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken); // 会执行到FilterSecurityInterceptor权限校验的过滤器，判断访问该请求是否具备对应的权限，有权限则访问成功，否则失败
        // 放行
        filterChain.doFilter(request, response);
    }
}
